const express = require('express');
const path = require('path');
const { WebSocketServer } = require('ws');
const cors = require('cors');
const multer = require('multer');
const { getLocalIP } = require('./utils/network.cjs');
const morgan = require('morgan');

const app = express();
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  exposedHeaders: ['Content-Length', 'X-Progress']
}));
app.use(morgan(':date[iso] :method :url :status :response-time ms', {
  stream: {
    write: (message) => console.log(`[API] ${message.trim()}`)
  }
}));

// 文件存储配置
const fs = require('fs');
// 默认production
const isProduction = (process.env.NODE_ENV || 'production') === 'production';
const configPath = isProduction? path.join(__dirname, '../../electron/config.json'): path.join(__dirname, 'config.json');

const getConfig = () => {
  try {
    console.log('正在读取配置文件:', configPath);
    const rawData = fs.readFileSync(configPath, 'utf8');
    return JSON.parse(rawData);
  } catch (err) {
    console.error('配置文件读取失败，使用默认配置:', err);
    return {
      renameFiles: true,
      overwriteExisting: true,
      storagePath: 'uploads'
    };
  }
};

// 内存存储配置（缓冲区扩大至500MB）
const storage = multer.memoryStorage();
const upload = multer({
  storage,
  limits: {
    fileSize: 1024 * 1024 * 1024, // 1GB
    parts: 100 // 允许最多100个并发分块
  }
});

// 分块上传临时存储
const chunkStorage = new Map();

// 分块上传接口
app.post('/upload-chunk', upload.single('chunk'), async (req, res) => {
  try {
    const { fileName, chunkIndex, totalChunks } = req.body;
    
    if (!req.file || !fileName || chunkIndex === undefined || !totalChunks) {
      return res.status(400).json({ error: 'Missing parameters' });
    }

    // 初始化分块存储
    if (!chunkStorage.has(fileName)) {
      chunkStorage.set(fileName, {
        total: parseInt(totalChunks),
        received: new Array(parseInt(totalChunks)).fill(false)
      });
    }

    // 存储分块数据
    const fileInfo = chunkStorage.get(fileName);
    fileInfo.received[parseInt(chunkIndex)] = {
      buffer: req.file.buffer,
      size: req.file.size
    };

    // 检查是否完成
    const completed = fileInfo.received.filter(Boolean).length === fileInfo.total;
    
    if (completed) {
      // 合并分块
      const config = getConfig();
      console.log('文件存储实时配置:', config);
      const uploadDir = path.resolve(__dirname, '..', config.storagePath);
      fs.mkdirSync(uploadDir, { recursive: true });
      
      // 生成最终文件名
      const originalName = config.renameFiles 
        ? Date.now() + '-' + fileName
        : fileName;

      let finalName = originalName;
      if (!config.overwriteExisting) {
        const ext = path.extname(originalName);
        const base = path.basename(originalName, ext);
        let counter = 1;
        while (fs.existsSync(path.join(uploadDir, finalName))) {
          finalName = `${base}_${counter}${ext}`;
          counter++;
        }
      }
      const finalPath = path.join(uploadDir, finalName);
      const writeStream = fs.createWriteStream(finalPath, { flags: 'a' });
      
      // 按分块顺序流式写入
      const writePromises = Array.from({ length: fileInfo.total }, (_, i) => {
        return new Promise((resolve, reject) => {
          writeStream.write(fileInfo.received[i].buffer, (err) => {
            if (err) reject(err);
            else resolve(true);
          });
        });
      });
      
      Promise.all(writePromises)
        .then(() => {
          writeStream.end(() => {
            chunkStorage.delete(fileName);
            res.status(200).json({
              path: finalPath,
              size: fs.statSync(finalPath).size
            });
          });
        })
        .catch(err => {
          writeStream.destroy();
          fs.unlinkSync(finalPath);
          res.status(500).json({ error: err.message });
        });
    } else {
      res.status(206).json({
        received: fileInfo.received
          .map((chunk, idx) => chunk ? idx : null)
          .filter(v => v !== null)
      });
    }
  } catch (err) {
    console.error('分块上传错误:', err);
    res.status(500).json({ error: err.message });
  }
});

// WebSocket服务
// const wss = new WebSocketServer({ port: 8081 });

// 文件上传端点
// 获取本机IP地址
app.get('/ip', (req, res) => {
  res.json({ ip: getLocalIP() });
});

app.get('/', (req, res) => {
  res.send('服务已就绪');
});

// 添加静态文件服务中间件
app.use(express.static('public'));

// 创建客户端服务实例
const clientApp = express();
const staticPath = isProduction
  ? path.join(__dirname, '../dist')
  : path.join(__dirname, '../dist');
clientApp.use(express.static(staticPath));
clientApp.get('*', (req, res) => {
  res.sendFile(path.join(staticPath, 'index.html'));
});

// 启动API服务
app.listen(3001, '0.0.0.0', () => {
  console.log(`API服务运行在 http://${getLocalIP()}:3001`);
});

// 启动客户端服务
clientApp.listen(3000, '0.0.0.0', () => {
  console.log(`客户端服务运行在 http://${getLocalIP()}:3000`);
});